<?

session_start();
include_once 'includes/utilities.php';
if (isset($_SESSION["protocolo"]))
{
    $link = OpenDB();
    $protocolo = $_SESSION["protocolo"];

    if (is_numeric($protocolo))
    {
        $pap = GetSQLFirstValue("select id_pap from pap where numero_protocolo = " . $protocolo);
        if (!is_numeric($pap))
        {
            $transaction = PostSQL("LOCK TABLES pap WRITE,  pap_diagnostico_pap WRITE");
            $pap = GetSQLFirstValue("select IFNULL(max(id_pap),0) + 1 from pap");
            $insert = PostSQL("insert into pap (id_pap, numero_protocolo) values (" . $pap . ", " . $protocolo . ")");
        } else
        {
            $clear = PostSQL("delete from pap_diagnostico_pap where id_pap = " . $pap);
        }
        foreach ($_POST as $key => $value)
        {
            if ($value == "on")
            {
                $insert = PostSQL("insert into pap_diagnostico_pap (id_pap, codigo_diagnostico_pap) values
                            (" . $pap . ", '" . $key . "')");
            }
        }
        $transaction = PostSQL("COMMIT");
        $transaction = PostSQL("UNLOCK TABLES");
        CloseDB($link);
    }
    CloseDB($link);
    header("Location: cargarProtocolo.php");
} else
{
    header("Location: error.php?error=No se encontro numero de protocolo");
}
?>
